package com.alcj.controller;


import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.model.Address;
import com.alcj.model.User;
import com.alcj.service.AddressService;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author :lihj
 * @version :v1.0
 * @Package :com.alcj.controller
 * @Description :${TODO}(收货地址)
 * @date :2017/10/30
 */
@Controller
@RequestMapping("/address")
public class AddressController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AddressService addressService;


    /**
     * @param request
     * @param model
     * @return String
     * @Author: guofsh
     * @Description:初期表示信息
     */
    @RequestMapping("/queryAddress")
    public String queryAddress(HttpServletRequest request, Model model) {
        try {
            // 获取登录用户
            User sysUser = (User) request.getSession().getAttribute("User");
            // 获取登录用户判断用户Id跟用户类型是否为空
            if (CmnUtil.isEmpty(sysUser)) {

                return SysConstant.INDEX_PAGE;

            } else {
                //取得用户Id
                String sysUserId = sysUser.getUserid();
                request.getSession().setAttribute("userId", sysUserId);
//                查询用户地址信息
                List<Address> list = addressService.getAddressInfos(sysUserId);
                model.addAttribute("listAddressSize", list.size());
                model.addAttribute("Address", new Address());
                //把用户地址信息存入model
                model.addAttribute("listAddress", list);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("获取收货地址信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "/address";
    }

    /**
     * @param request
     * @param model
     * @return String
     * @Author: guofsh
     * @Description:修改地址
     */
    @RequestMapping("updateAddress")
    @ResponseBody
    public JSONObject updateAddress(HttpServletRequest request, Model model) {
        JSONObject resultJson = new JSONObject();
        try {
            String userId = request.getSession().getAttribute("userId").toString();
            request.getSession().setAttribute("userId", userId);
            // 获取登录用户判断用户Id跟用户类型是否为空
            if (request.getSession().getAttribute("userId") == null) {

                return resultJson;

            } else {
                //获取地址id
                String addressId = request.getParameter("addressid");
                Address address = addressService.getAddressInfo(addressId);

                resultJson.put("districts", address.getDistrict().split(" "));
                resultJson.put("Address", address);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("修改收货地址信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return resultJson;
        }
        return resultJson;
    }

    /**
     * @param request
     * @param model
     * @return String
     * @Author: guofsh
     * @Description:删除地址
     */
    @RequestMapping("deleteAddress")
    @ResponseBody
    public JSONObject deleteAddress(HttpServletRequest request, Model model) {
        JSONObject resultJson = new JSONObject();
        try {
            //测试数据
            String sysUserId = request.getSession().getAttribute("userId").toString();
            request.getSession().setAttribute("userId", sysUserId);
            // 获取登录用户判断用户Id是否为空
            if (request.getSession().getAttribute("userId") == null) {

                return resultJson;

            } else {
                Address address = new Address();
                //获取地址id
                String addressId = request.getParameter("addressid");
                address.setAddressid(addressId);
                address.setOptiontime(new Date());
                addressService.deleteAddress(address);
                List<Address> list = addressService.getAddressInfos(sysUserId);
                resultJson.put("addressList", list);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("删除收货地址信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return resultJson;
        }
        return resultJson;
    }

    /**
     * @param request
     * @param model
     * @return String
     * @Author: lihj
     * @Description:添加地址
     */
    @RequestMapping("insertAddress")
    public String insertAddress(HttpServletRequest request, Model model) {
        try {
            //测试数据
            String userId = request.getSession().getAttribute("userId").toString();
            request.getSession().setAttribute("userId", userId);
            // 获取登录用户判断用户Id跟用户类型是否为空
            if (request.getSession().getAttribute("userId") == null) {

                return SysConstant.INDEX_PAGE;

            } else {
                //取得用户Id
                Address address = new Address();
                String sysUserId = request.getSession().getAttribute("userId").toString();
                //操作人
                address.setOperaid(sysUserId);
                //收货人电话
                address.setTelPhone(request.getParameter("telPhone").toString());
                //是否为默认地址
                String[] listdelFlag = request.getParameterValues("delFlag");
                if (listdelFlag != null) {
                    address.setDelFlag("1");
                    addressService.updatedelFlagByOperaId(sysUserId);
                } else {
                    address.setDelFlag("0");
                }
                //收货人姓名
                address.setConsignee(request.getParameter("consignee").toString());
                //详细地址
                address.setAddress(request.getParameter("address").toString());
                //选择地区
                address.setDistrict(request.getParameter("province") + " " + request.getParameter("city") + " " + request.getParameter("area"));
                //邮编
                address.setPostalcode(request.getParameter("postalcode").toString());
                //是否删除
                address.setDelflag("0");
                //操作时间
                address.setOptiontime(new Date());
                //地址Id,生成唯一标识
                if (request.getParameter("addressidOne") != null && request.getParameter("addressidOne") != "") {
                    address.setAddressid(request.getParameter("addressidOne").toString());
                    addressService.updateAddressInfo(address);
                } else {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    address.setAddressid(uuid);
                    addressService.setAddressInfo(address);
                }

//                查询用户地址信息
                List<Address> list = addressService.getAddressInfos(sysUserId);
                model.addAttribute("listAddressSize", list.size());
                //把用户地址信息存入model
                model.addAttribute("listAddress", list);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("插入收货地址信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "redirect:/address/queryAddress";

    }

    /**
     * @param request
     * @param model
     * @return String
     * @Author: guofsh
     * @Description:设置默认地址
     */
    @RequestMapping("delFlagAddress")
    @ResponseBody
    public JSONObject delFlagAddress(HttpServletRequest request, Model model) {
        JSONObject resultJson = new JSONObject();
        try {
            String sysUserId = request.getSession().getAttribute("userId").toString();
            request.getSession().setAttribute("userId", sysUserId);
            // 获取登录用户判断用户Id是否为空
            if (request.getSession().getAttribute("userId") == null) {

                return resultJson;

            } else {
//                Address address = new Address();
                //获取地址id
                String addressId = request.getParameter("addressid");
//                address.setAddressid(addressId);
                addressService.updatedelFlagByOperaId(sysUserId);
//                address.setOptiontime(new Date());
                addressService.updatedelFlagByPrimaryKey(addressId);
                List<Address> list = addressService.getAddressInfos(sysUserId);
                resultJson.put("addressList", list);
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("删除收货地址信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return resultJson;
        }
        return resultJson;
    }
}
